package scau.hotel.hotel_sys.service.Impl;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import scau.hotel.hotel_model.controller.RespBean;
import scau.hotel.hotel_model.controller.RespBeanEnum;
import scau.hotel.hotel_sys.entity.SysUser;
import scau.hotel.hotel_sys.entity.SysUserRole;
import scau.hotel.hotel_sys.mapper.SysUserMapper;
import scau.hotel.hotel_sys.mapper.SysUserRoleMapper;
import scau.hotel.hotel_sys.service.ISysUserRoleService;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * (SysUserRole)表服务实现类
 *
 * @author makejava
 * @since 2022-04-20 15:53:34
 */
@Service("sysUserRoleService")
public class ISysUserRoleServiceImpl implements ISysUserRoleService {
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public SysUserRole queryById(Long id) {
        return this.sysUserRoleMapper.queryById(id);
    }

    /**
     * 查询所有
     *
     * @param sysUserRole 筛选条件
     * @return 查询结果
     */
    @Override
    public List<SysUserRole> queryAll(SysUserRole sysUserRole) {
        return this.sysUserRoleMapper.queryAll(sysUserRole);
    }

    /**
     * 分页查询
     *
     * @param sysUserRole 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public Page<SysUserRole> queryByPage(SysUserRole sysUserRole, PageRequest pageRequest) {
        long total = this.sysUserRoleMapper.count(sysUserRole);
        return new PageImpl<>(this.sysUserRoleMapper.queryAllByLimit(sysUserRole, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param sysUserRole 实例对象
     * @return 实例对象
     */
    @Override
    public SysUserRole insert(SysUserRole sysUserRole) {
        this.sysUserRoleMapper.insert(sysUserRole);
        return sysUserRole;
    }

    /**
     * 修改数据
     *
     * @param sysUserRole 实例对象
     * @return 实例对象
     */
    @Override
    public SysUserRole update(SysUserRole sysUserRole) {
        this.sysUserRoleMapper.update(sysUserRole);
        return this.queryById(sysUserRole.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public RespBean deleteById(Long id) {
        SysUser user = this.sysUserMapper.queryById(this.sysUserRoleMapper.queryById(id).getUserId());
        //root账号权限无法解除
        if (Objects.equals(user.getUsername(), "root") && user.getId() == 1){
            return RespBean.error(RespBeanEnum.UNAUTHORIZED_ERROR,"该权限无法解除！请联系开发者");
        }else {
            this.sysUserRoleMapper.deleteById(id);
            return RespBean.success("删除成功");
        }
    }
}
